package ua.pp.bizon.yandex.uploader.atom;

import ua.pp.bizon.yandex.api.IHTTPUtils;
import ua.pp.bizon.yandex.api.IUserDataManager;
import ua.pp.bizon.yandex.api.ObjectLookup;

import java.io.StringReader;
import java.util.List;

import org.apache.abdera.model.Document;
import org.apache.abdera.model.Element;
import org.apache.abdera.parser.stax.FOMParserFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpResponseException;

public class PhotosListFactory {

	private static Log LOG = LogFactory.getLog(PhotosListFactory.class);

	public static PhotosList create(AppLink photosLink) {
		PhotosList list = new PhotosList();
		LOG.debug("start parse photos list for " + photosLink);
		create(photosLink, list);
		LOG.debug("end parse photos list for " + photosLink);
		return list;
	}

	protected static void create(AppLink photosLink, PhotosList list) {
		String token = ObjectLookup.lookup(IUserDataManager.class).get().getToken();
		String response = null;
		do {
			try {
				response = ObjectLookup.lookup(IHTTPUtils.class).get(photosLink.getLink(), token);
			} catch (HttpResponseException e1) {
				LOG.warn("photoslink is incorrect", e1);
			}
		} while (response == null);
		Document<Element> document = new FOMParserFactory().getParser().parse(new StringReader(response));
		List<Element> tokens = document.getRoot().getElements();
		for (Element e : tokens) {
			if (e.getQName().getLocalPart().equals("link")) {
				AppLink link = new AppLink(e);
				if ("next".equals(link.getRel())) {
					LOG.debug("next link has being found");
					create(link, list);
				}
			}
			if (e.getQName().getLocalPart().equals("author")) {
				list.setAutorName(e.getElements().get(0).getText());
			} else if (e.getQName().getLocalPart().equals("entry")) {
				Photo photo = new Photo(e);
				list.addPhoto(photo);
			}
		}
	}

}
